package de.imdb250junkie.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.UIManager;

import de.imdb250junkie.db.DB;
import de.imdb250junkie.gui.MainWindow;
import de.imdb250junkie.gui.UpdateDoneListener;
import de.imdb250junkie.gui.UpdateWindow;

/**
 * @author André Stannek
 * @version 2010-02-10
 */
public final class Loader
{
    /**
     * 
     */
    private static DB database;

    /**
     * @param args
     *            no arguments taken
     * @throws IOException
     *             if the serialized file could not be read
     */
    public static void main(final String[] args) throws IOException
    {
        // activate system look & feel
        try
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (final Exception e)
        {
            Logger.getLogger("ERROR").log(Level.WARNING,
                    "System look and feel could not be loaded", e);
        }

        load();
    }

    /**
     * Load an old DB object from default path if possible or creates a new one.
     * After Database is fully loaded it creates a new {@link MainWindow}.
     */
    public static void load()
    {
        load("db.ser");
    }

    /**
     * Load an old DB object if possible or creates a new one. After Database is
     * fully loaded it creates a new {@link MainWindow}.
     * 
     * @param path
     *            path to serialized database file
     */
    public static void load(final String path)
    {
        try (ObjectInputStream objectIn = new ObjectInputStream(
                new FileInputStream(path)))
        {
            final Object input = objectIn.readObject();
            if (input instanceof DB)
            {
                database = (DB) input;
                database.makeTop();
                new MainWindow(database);
            }
            else
            {
                onFailure();
            }
        }
        catch (final IOException | ClassNotFoundException e)
        {
            onFailure();
        }
    }

    private static void onFailure()
    {
        database = new DB();
        new UpdateWindow(database, new UpdateDoneListener()
        {
            @Override
            public void done()
            {
                new MainWindow(database);
            }
        });
    }

    /**
     * masking default constructor.
     */
    private Loader()
    {
        /**/
    }
}
